package com.ihome.android.market2.view;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ihome.android.EAApp;
import com.ihome.android.common.ConfigUtil;
import com.ihome.android.dl.core.DownloadHelper;
import com.ihome.android.dl.core.DownloadTask;
import com.ihome.android.dl.util.DLFileInfo;
import com.ihome.android.dl.util.DownloadValues;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.academy.R;
import com.ihome.android.market2.asynctask.InstallAppTask;
import com.ihome.android.util.BgInstallApk;
import com.ihome.android.util.Tools;
import com.ihome.android.util.log.LogUtil;
import com.ihome.android.util.log.UserBehaviorLog;
import com.ihome.android.util.log.UserBehaviorLog.NotifyType;
import com.ihome.android.util.log.UserBehaviorLog.UserBehavior;
import com.ihome.android.market2.view.DialogFactory;

public class DownloadDialog extends Dialog implements OnClickListener {
	private final String	TAG			= DownloadDialog.class.getSimpleName();
	private TextView		fileTitle;
	private TextView		fileSize;
	private TextView		fileUpdate;
	private ProgressBar		progressBar;
	private Button			btnOK;
	private Button			btnCancel;
	private Context			context;

	private String			fileName	= "";
	private String			url			= "";
	private String			pkgName		= "";
	private String			appMD5		= "";

	private Handler			mHandler;

	private void procHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				DownloadTask task = null;
				if (msg.obj instanceof DownloadTask) {
					task = (DownloadTask) msg.obj;
				}

				switch (msg.what) {
				case DownloadValues.Types.COMPLETE:
					handleCompletedAction(task.getAppInfo());
					break;
				case DownloadValues.Types.PROCESS:
					handleProgress(task);
					break;
				case DownloadValues.Types.ERROR:
					handleError(task.getAppInfo(), task.getErrorCode(), task.getErrorInfo());
					break;
				default:
					break;
				}
			}
		};
	}

	public DownloadDialog(Context context, String fileName, String url, String packName,String md5) {
		super(context, R.style.dialog);
		this.context = context;
		this.fileName = fileName.contains(".apk") ? fileName : fileName + ".apk";
		this.url = url;
		this.pkgName = packName;
		this.appMD5 = md5;
		LogUtil.d(TAG, "DownloadDialog() --> fileName = " + fileName + "url = " + url + "md5 = " + md5);

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog_donwload);

		LogUtil.d(TAG, "onCreate() -->");
		procHandler();
		EAApp.getApp().addHandler(mHandler);

		fileTitle = (TextView) findViewById(R.id.tv_dl_title);
		fileSize = (TextView) findViewById(R.id.tv_dl_size);
		fileUpdate = (TextView) findViewById(R.id.tv_dl_progress_text);
		progressBar = (ProgressBar) findViewById(R.id.pb_dl_progress);
		btnOK = (Button) findViewById(R.id.btn_dl_ok);
		btnCancel = (Button) findViewById(R.id.btn_dl_cancel);

		btnOK.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
		setCancelable(false);
		fileTitle.setText(fileName);

		DLFileInfo picFileInfo = new DLFileInfo();
		picFileInfo.setFilePath(ConfigUtil.FILE_PATH);
		picFileInfo.setFileUrl(url);
		picFileInfo.setFileType("apk");
		picFileInfo.setFileName(fileName);
		picFileInfo.setPkgName(pkgName);
		picFileInfo.setMD5(appMD5);
		addDLFile(picFileInfo);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		LogUtil.d(TAG, "--> onStop");
		EAApp.getApp().clearHandler(mHandler);
	}

	/**
	 * 
	 * 文件下载成功
	 * 
	 * @param dLFileInfo
	 * @see [类、类#方法、类#成员]
	 */
	private void handleCompletedAction(DLFileInfo dLFileInfo) {
		String filePath = dLFileInfo.getFilePath() + dLFileInfo.getFileName();
		LogUtil.d(TAG, "Download CompletedAction ---> filePath = " + filePath);

		if (EAApp.isSystemApp) {
			Bundle b = new Bundle();
			b.putString(HttpKeys.KEY_APKPATH, filePath);
			new InstallAppTask(context).execute(b);
		}
		else {
			BgInstallApk.doInstallation(context, filePath);
		}

		dismiss();
	}

	/**
	 * 
	 * 更新当前apk下载进度
	 * 
	 * @param dLFileInfo
	 * @param speed
	 * @param progress
	 * @see [类、类#方法、类#成员]
	 */
	private void handleProgress(DownloadTask task) {
		String speed = task.getDownloadSpeed() + "kbps | " + Tools.formateFileSize(getContext(), task.getDownloadSize()) + " / " + Tools.formateFileSize(getContext(), task.getTotalSize());
		String progress = task.getDownloadPercent() + "";
		LogUtil.v(TAG, " handleProgress  ---> speed = " + speed + "; progress = " + progress);
		progressBar.setProgress(Integer.parseInt(progress));
		fileUpdate.setText(progress + "%");
		fileSize.setText(speed);
	}

	/**
	 * 
	 * 解决下载过程中的错误
	 * 
	 * @param dLFileInfo
	 */
	public void handleError(DLFileInfo dLFileInfo, int errorCode, String errorInfo) {
		dismiss();
		new DialogFactory(getContext()).showDialog(EAApp.getApp().getString(R.string.attention_error), errorInfo);
		String[] msg = {"","","","","",""};
		UserBehaviorLog.getInstance().writeLog(UserBehavior.APPDOWNLOAD_EXCEPTION, NotifyType.TYPE_EXCEPTION, "", msg);
	}

	/**
	 * 增加下载任务
	 */
	private void addDLFile(DLFileInfo dLFileInfo) {
		LogUtil.d(TAG, "Add DL File() --> = " + dLFileInfo.getFilePath() + dLFileInfo.getFileName());
		DownloadHelper.addNewTask(context, dLFileInfo, new DownloadHelper.PreDownloadStatusListener() {

			@Override
			public void sdCardCannotWriteOrRead(int errorCode, String errorInfo) {
				Toast.makeText(context, "不能读写SD卡", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void notFoundSDCard(int errorCode, String errorInfo) {
				Toast.makeText(context, "没有SD卡", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void moreTaskCount(int errorCode, String errorInfo) {
				Toast.makeText(context, "任务列表已满", Toast.LENGTH_SHORT).show();
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_dl_ok:
			break;
		case R.id.btn_dl_cancel:
			dismiss();
			break;
		}
	}

}
